# 引入 jdango框架中 http模块中HttpResponse函数
from django.http import HttpResponse
# render 响应HTML文档的函数
from django.shortcuts import render
# 重定向
from django.shortcuts import redirect
#
from myjdango.models import User, Shop, Cars
import math


# 设置处理函数
def hw(request):
    return HttpResponse('你好')

#首页
def date(request):
    # name = request.GET.get('name')
    # naem 值获取 和session关联 uid是否存在
    if request.session.get('uid', None):
        # 有值判断为True 说明登录过
        # 先从数据库查询uid，再通过uid，拿到username
        name = User.objects.filter(uid=request.session['uid'])[0].username
    else:
        # 无值 判读false
        name = None
    stuname = '叶晨'
    sorce = 67
    shop = Shop.objects.all()
    # date = [
    #     {'shopNo': 9527, 'shopname': "红米手机",'shopimg': "/static/img/nmcil命令.png", 'shopgrade':2599, 'shopnum': 10},
    #     {'shopNo': 10000, 'shopname': "红米note", 'shopimg': "/static/img/nmcil命令.png", 'shopgrade': 1999, 'shopnum': 30},
    #     {'shopNo': 10001, 'shopname': "小米11", 'shopimg': "/static/img/nmcil命令.png", 'shopgrade': 2999, 'shopnum': 50},
    #     {'shopNo': 10086, 'shopname': "红米k50", 'shopimg': "/static/img/nmcil命令.png", 'shopgrade': 2369, 'shopnum': 90},
    #     {'shopNo': 365, 'shopname': "小米12Utrl", 'shopimg': "/static/img/nmcil命令.png", 'shopgrade': 4599, 'shopnum': 5}
    # ]

    # 搜索功能
    search = request.GET.get('search')
    error_message = ''
    if search:
        shop = Shop.objects.filter(shop_name__icontains=search).all()
    else:
        shop = Shop.objects.all()
    # 计算总页码 ,给前端传递的页码列表，pagelist math.ceil()向上取整
    # 封装函数rang（start，end） 自动生成从start（包含start）开始，到end（不包含end）结束
    pagelist = range(1, math.ceil(len(shop) / 5) + 1)

    # 接受前端传递的页码
    page_num = request.GET.get('page_num')
    if page_num:
        # 有值为字符串 转化为 整数
        page_num = int(page_num)
    else:
        # 无值 默认展示第一页
        page_num = 1
        # 截取数据库查询的结果的前5个   列表切片
    shop = shop[5 * (page_num - 1):5 * page_num]
    return render(request, 'index.html',
                  {'date': shop, 'stuname': stuname, 'sorce': sorce, 'name': name, 'pagelist': pagelist})


# 登录页面
def login(request):
    if request.method == 'POST':
        username = request.POST.get('username')
        userpasswd = request.POST.get('userpasswd')
        result = User.objects.filter(username=username)
        if result:
            # 判断一下，当前有值的账号对应的密码和 前端发送的密码是否存在
            if result[0].userpassword == userpasswd:
                # 登录成功，将用户的uid存入session中
                request.session['uid'] = result[0].uid
                # 重定向到index页面同时将index函数里面的数据带过去
                return redirect('/index/?name=' + result[0].username)
            else:
                # 账号存在 密码错误
                return render(request, 'login.html')
        else:
            # 账号不存在
            return render(request, 'register.html')
    else:
        return render(request, 'login.html')


# 登录页面
# def login(request):
#     context = {}
#     if request.method == "GET":
#         return render(request, "login.html")
#     if request.method == "POST":
#         name = request.POST.get('username')
#         password = request.POST.get('userpasswd')
#         if all([name, password]):
#             user = User.objects.filter(username=name).first()
#             if not user:
#                 context['message'] = "用户不存在"
#                 return redirect('/register/')
#             else:
#                 if name == user.username and password == user.userpassword:
#                     return redirect('/index/')
#                 context['message'] = "密码错误"
#         else:
#             context['message'] = "参数不全"
#         return render(request, "login.html", context)


def register(request):  # 注册
    if request.POST:
        username = request.POST.get('username')
        userpasswd = request.POST.get('userpasswd')
        # 拿到值，插入数据库
        # 将用户类 实例化 对象
        # user1 = User(uid=1,username=username,userpassword=userpasswd)
        ##数据保存
        # user1.save()
        # 方法二
        User.objects.create(username=username, userpassword=userpasswd)
        return redirect('/login/')
    return render(request, 'register.html')


# 导航栏
def getnav(request):
    one = [
        {'type': '玄幻', 'select': [
            {'chices': '武动乾坤', 'select1': [{
                'chices1': '林动'}, {'chices1': '凌清竹'}, {'chices1': '凌笑笑'}, {'chices1': '祖符'}]},
            {'chices': '斗罗大陆', 'select1': [{
                'chices1': '唐三'}, {'chices1': '小舞'}, {'chices1': '沐白'}, {'chices1': '奥斯马'}]},
            {'chices': '大主宰', 'select1': [{
                'chices1': '牧尘'}, {'chices1': '九幽雀'}, {'chices1': '铁浮屠'}, {'chices1': '域外天魔'}]},
            {'chices': '斗破苍穹', 'select1': [{
                'chices1': '萧炎'}, {'chices1': '萧熏儿'}, {'chices1': '美杜莎'}, {'chices1': '药尘'}]}]},
        {'type': '武侠', 'select': [
            {'chices': '天龙八部', 'select1': [{
                'chices1': '乔峰'}, {'chices1': '段誉'}, {'chices1': '虚竹'}, {'chices1': '阿紫'}]},
            {'chices': '神雕侠侣', 'select1': [{
                'chices1': '杨过'}, {'chices1': '小龙女'}, {'chices1': '郭襄'}, {'chices1': '欧阳锋'}]},
            {'chices': '倚天屠龙记', 'select1': [{
                'chices1': '张无忌'}, {'chices1': '赵敏'}, {'chices1': '周慧敏'}, {'chices1': '张三丰'}]},
            {'chices': '笑傲江湖', 'select1': [{
                'chices1': '令狐冲'}, {'chices1': '东方不败'}, {'chices1': '任盈盈'}, {'chices1': '风清扬'}]}
        ]},
        {'type': '仙侠', 'select': [
            {'chices': '凡人修仙传', 'select1': [
                {'chices1': '韩立'}, {'chices1': '炼妖壶'}, {'chices1': '乱星海'}, {'chices1': '韩跳跳'}]},
            {'chices': '诛仙', 'select1': [
                {'chices1': '张小凡'}, {'chices1': '兽神'}, {'chices1': '九天引雷剑诀'}, {'chices1': '诛仙剑'}]},
            {'chices': '洪荒', 'select1': [{
                'chices1': '鸿钧'}, {'chices1': '太清'}, {'chices1': '玉清'}, {'chices1': '上清'}]},
            {'chices': '完美世界', 'select1': [{
                'chices1': '石昊'}, {'chices1': '至尊骨'}, {'chices1': '原始剑胎'}, {'chices1': '十凶法'
                                                                            }]}]},
        {'type': '历史', 'select': [
            {'chices': '大秦', 'select1': [{
                'chices1': '嬴政'}, {'chices1': '白起'}, {'chices1': '蒙恬'}, {'chices1': '王翦'}]},
            {'chices': '大唐', 'select1': [{
                'chices1': '李世民'}, {'chices1': '程咬金'}, {'chices1': '魏征'}, {'chices1': '观音婢'}]},
            {'chices': '大明', 'select1': [{
                'chices1': '朱元璋'}, {'chices1': '徐长达'}, {'chices1': '刘伯温'}, {'chices1': '蓝玉'
                                                                            }]}, {'chices': '三国', 'select1': [{
                'chices1': '刘备'}, {'chices1': '曹操'}, {'chices1': '孙权'}, {'chices1': '诸葛亮'}]}]}
    ]
    return render(request, 'nav.html', {'one': one})


# 搜索
def search(request):
    search = request.GET.get('search')
    error_message = ''
    if not search:
        error_message = '请输入关键字'
        return render(request, 'index.html', {'error_message': error_message})
    search_list = Shop.objects.filter(shop_name=search).all()
    return render(request, 'index.html', {'search_list': search_list})


# 加入购物车
def content_type(request):
    # 接受前端传递来的信息,商品id参数
    shop_id = request.GET.get('shop_id')
    #接收 详情页加入购物车传递 ，商品id input按钮传参
    if request.POST:
        if request.session.get('uid', None):
            shop_id = request.POST.get('car_shop_id')
            uid = request.session.get('uid')
            #car = Cars(shop_id=shop_id, buy_count=1, uid=uid)
            #先查询数据库shop表中shop_id对应商品信息数据吗，在插入购物车表中
            #filter查询出来的是列表，first()表示的是列表中的第一个
            shop = Shop.objects.filter(shop_id=shop_id).first()
            car = Cars(shop=shop,buy_count=1,uid=uid)
            car.save()
        else:
            return redirect('/login/')
    # 根据参数执行数据库操作 条件查询filter
    keys_list = Shop.objects.filter(shop_id=shop_id)

    # 详情页加入购物车传递 ，商品id, a标签传参
    # car_shop_id = request.GET.get('car_shop_id')
    # if car_shop_id:
    # 根据参数执行数据库操作，插入数据
    # Cars.objects.create(cid=None,shop_id=car_shop_id,buy_count=1)
    # keys_list = Shop.objects.filter(shop_id=car_shop_id).first()
    # print(keys_list)

    return render(request, 'content.html', {'keys_list': keys_list})


# 购物车显示页面
def show_myshopcar(request):
    # 先判断 判断是否登录 用request.session对象中是否存在键uid的值
    if request.session.get('uid', None):  # 有值 True 说明有登录
        # 获取session中的uid
        uid = request.session['uid']
        # 数据库操作，查询操作 购物车表
        cars = Cars.objects.filter(uid=uid)
        # 数据库查询结果 car 【{cid,shop_id,buy_count,uid}，{}，{}。。。】
        # 数据库查询结果 car 【{cid,shop,buy_count,uid}，{}，{}。。。】有外键之后
        shops = []  # 设定 响应前端页面的所有购物车商品数据的列表
        for item in cars:
            # item{cid,shop_id,buy_count,uid}
            # 有外键之后item{cid,shop,buy_count,uid}
            # 查出来的结果为 [{shop_id}]
            #shop = Shop.objects.filter(shop_id=item.shop_id)[0]将id查询出来
            # shop = {shop_id,shop_name,shop_img,shop_price,shop_num}第一个是id
            shop = item.shop
            shop.buy_count = item.buy_count
            shop.allPrice = int(item.buy_count) * float(shop.shop_price)
            shops.append(shop)
        return render(request, 'myshopcars.html', {'shops': shops, 'cars': cars})
    else:  # 无值 false 说明没有登录
        return redirect('/login/')


# 退出登录
def logout(request):
    # 清除所有的存储在session中的uid
    # 删除session对象uid键值对，实质对数据库中session表修改session_data字段值
    # request.session.pop('uid')
    # del request.session['uid']
    # request.session.clear()

    #删除数据库中session表中 的记录（数据）把一行都删除了，把一个列表删除了
    request.session.delete(request.session.session_key)
    request.session.flush()
    return redirect('/index/')
